package com.rafael.teste.filtros;

import java.io.IOException;

import javax.persistence.EntityManagerFactory;
import javax.persistence.Persistence;
import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.annotation.WebFilter;

import org.hibernate.Session;

import com.rafael.teste.enumerators.Conexao;

@WebFilter(servletNames = { "Faces Servlet" })
public class ConexaoHibernateFiltro implements Filter {

	EntityManagerFactory factory;

	@Override
	public void destroy() {
		this.factory.close();
	}

	@Override
	public void doFilter(ServletRequest request, ServletResponse response,
			FilterChain chain) throws IOException, ServletException {

		Session session = this.factory.createEntityManager().unwrap(
				Session.class);

		try {
			session.beginTransaction();
			chain.doFilter(request, response);
			session.getTransaction().commit();
			session.close();
		} catch (Throwable e) {
			try {
				if (session.getTransaction().isActive()) {
					session.getTransaction().rollback();
				}
			} catch (Throwable t) {
				t.printStackTrace();
			}
			throw new ServletException(e.getMessage());
		}
	}

	@Override
	public void init(FilterConfig cfg) throws ServletException {
		this.factory = Persistence
				.createEntityManagerFactory(Conexao.PERSISTENCE_UNIT.getValor());
	}
}
